package com.yearner.reviewplan.user;

import com.google.gson.Gson;
import com.yearner.reviewplan.common.util.MD5Util;
import com.yearner.reviewplan.common.util.MyJdbcUtil;
import com.yearner.reviewplan.user.exceptions.UserNotFoundException;
import com.yearner.reviewplan.user.model.User;
import com.yearner.reviewplan.user.model.UserBaseRepository;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;

import static com.yearner.reviewplan.user.enums.UserTableEnum.*;
/**
 * @author pengyg
 * @since 2019/10/16
 */
@Repository
public class UserRepresentation extends UserBaseRepository {


    public UserRepresentation(MyJdbcUtil myJdbcUtil, Gson gson) {
        super(myJdbcUtil, gson);
    }

    public User login(String account, String password) {
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
            return null;
        }
//        String sql = "select * from user " +
//                "where 1=1 and account_contain-> '$.accountName' = ? and account_contain ->'$.newPassword' = ?";

//        String sql = String.format("select * from %s where %s = ? and %s = ?",TABLE.getColumn(),ACCOUNT.getColumn(),PASSWORD.getColumn());
        String md5Pwd = MD5Util.MD5EncodeUtf8Salt(password);
        String sql = getOneAndOneSql(TABLE.getColumn(), ACCOUNT.getColumn(), PASSWORD.getColumn());
        List<User> userList = jdbcTemplate.query(sql, mapper(), account, md5Pwd);

        if (userList.isEmpty()) {
            throw new UserNotFoundException();
        }
        return userList.get(0);
    }

//
//    @Override
//    protected RowMapper<User> mapper() {
//        return (rs, rowNum) -> {
//            UserId userId = UserId.byId(rs.getString(ID.getColumn()));
////            return User.create(userId, account);
//
//            return UserFactory.create(
//                    userId,
//                    rs.getString(ACCOUNT.getColumn()),
//                    rs.getString(PASSWORD.getColumn()),
//                    gson.fromJson(rs.getString(CYCLE.getColumn()), Cycle.class)
//            );
//        };
//    }

    /**
     * 通过id来获取
     * @param userId
     * @return
     */
    public User getById(String userId) {
        String sql = String.format("select * from %s where %s = ?",TABLE.getColumn(),ID.getColumn());
        List<User> query = jdbcTemplate.query(sql, mapper(), userId);
        if (query.isEmpty()) {
            throw new RuntimeException("用户ID有误！");
        }
        return query.get(0);
    }
}
